package cn.itcast.service.impl;

import cn.itcast.constant.JwtClaimsConstant;
import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.WeChatConstant;
import cn.itcast.exception.LoginFailedException;
import cn.itcast.properties.JwtProperties;
import cn.itcast.properties.WeChatProperties;
import cn.itcast.mapper.UserMapper;
import cn.itcast.service.UserService;
import cn.itcast.utils.HttpClientUtil;
import cn.itcast.utils.JwtUtil;
import cn.itheima.users.dto.UserLoginDTO;
import cn.itheima.users.pojo.User;
import cn.itheima.users.vo.UserLoginVO;
import cn.itheima.users.vo.UserReportVO;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private WeChatProperties weChatProperties;

    private JwtProperties jwtProperties;

    private UserMapper userMapper;

    /**
     * 用户端微信登录
     *
     * @param userLoginDTO 请求参数
     * @return 用户的登录信息
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {

        //1. 通过code去wx平台 拿到用户唯一的openid
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type", "authorization_code");
        //发送请求
        String body = HttpClientUtil.doGet(WeChatConstant.WX_LOGIN, param);
        String openid = (String) JSONObject.parseObject(body).get("openid");

        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2. id，用户id
        //向user表中添加一条数据，主要就是保存openid
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            //说明表中没有openid，是新用户，添加操作
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

            userMapper.insert(user);  //主键自增返回
        }

        //3. token
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(), //jwt加密密钥
                jwtProperties.getUserTtl(),
                claims);

        return UserLoginVO.builder()
                .openid(openid)
                .id(user.getId())
                .token(token)
                .build();
    }

    @Override
    public User getById(long id) {
        return userMapper.getById(id);
    }

    @Override
    public List<UserReportVO> countByTime(LocalDate begin, LocalDate end) {
        return userMapper.countByTime(begin, end);
    }
}
